package framework.ui;


import org.openems.entity.ChoiceEntity;
import org.openems.entity.Entity;
import org.openems.entity.Key;

import javafx.scene.control.Label;
import framework.DomainService;
import framework.EntityStoreListener;

public class EmsComboConnector {
	private boolean ignoreChangeEvent = true;
	
	public EmsComboConnector(ILabel title, final IComboBox choice,
			final DomainService service, Key key) {
		
		final ChoiceEntity entity = (ChoiceEntity)service.getEntity(key);
		title.setText(entity.getName());		
		
		choice.setElements(entity.getChoices());
		choice.setOnChange(new IComboListener() {

			@Override
			public void changed(int index) {
				if (!ignoreChangeEvent) {
					entity.setIndex(index);
					service.putEntity(entity);
				}
			}
			
		});	
		
		service.addEntityStoreListener(new EntityStoreListener() {
			@Override
			public void valueChanged(Entity entity) {
				ChoiceEntity e = (ChoiceEntity)entity;
				ignoreChangeEvent = true;
				choice.setElements(e.getChoices());
				choice.setSelectedIndex(e.getIndex());
				ignoreChangeEvent = false;
			}
			
		}, key);
		
		choice.setSelectedIndex(entity.getIndex());
		
		ignoreChangeEvent = false;
	}

}
